package com.yunshipei.ui.activity;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.fsck.k9.Account;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.controller.MessagingListener;
import com.kyleduo.switchbutton.SwitchButton;
import com.yunshipei.adapter.MyListViewAdapter;
import com.yunshipei.base.BaseActivity;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.base.EnterBaseSubscriber;
import com.yunshipei.common.Globals;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.UserInfo;
import com.yunshipei.model.YspEvent;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.YspProtocolUtils;
import com.yunshipei.utils.StringUtil;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONObject;

import java.util.List;

import io.rong.app.utils.StringUtilSub;
import io.rong.eventbus.EventBus;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation.ConversationType;


public class DetailContactsActivity extends BaseActivity {
    private UserInfo userInfo, myInfo;
    private TextView nameTV, positionTV, groupTV, emailTV, phoneTV;
    private ImageView avatar, telBtu, imBtu;
    private TextView nameTitle;
    private SharedPreferences mySharedPreferences;
    private YspTitleBar mTitleBar;
    private SwitchButton commonCheckbox;
    private WaitDialog mDialog;
    private boolean shouldListen = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_detail);
        mySharedPreferences = YspPreferences.getInstance().getSharedPreferences();
        myInfo = (UserInfo) StringUtilSub.getEncodeBase64(mySharedPreferences.getString(Globals.YSP_USER_INFO, ""));
        initView();
        initData();
    }

    private void initView() {
        mTitleBar = (YspTitleBar) findViewById(R.id.title_bar);
        nameTitle = (TextView) findViewById(R.id.nametitle);
        nameTV = (TextView) findViewById(R.id.nametv);
        positionTV = (TextView) findViewById(R.id.positiontv);
        groupTV = (TextView) findViewById(R.id.groupId);
        emailTV = (TextView) findViewById(R.id.emailaddr);
        phoneTV = (TextView) findViewById(R.id.phonenumber);
        View.OnLongClickListener longClickListener = new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                CharSequence text = ((TextView) v).getText();
                if (!TextUtils.isEmpty(text)) {
                    ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    cm.setPrimaryClip(ClipData.newPlainText("", text));
                    ToastUtils.showToast("复制成功");
                    return true;
                }
                return false;
            }
        };
        emailTV.setOnLongClickListener(longClickListener);
        phoneTV.setOnLongClickListener(longClickListener);
        avatar = (ImageView) findViewById(R.id.imageView1);
        telBtu = (ImageButton) findViewById(R.id.telBut);
        imBtu = (ImageButton) findViewById(R.id.imBut);
        commonCheckbox = (SwitchButton) findViewById(R.id.common_checkbox);
        //commonCheckbox.setTintColor(EnterConfig.getInstance().getGlobalColor());
        commonCheckbox.setBackColor(BaseUtil.getCurrentSwitchButtonColor(this));
        mDialog = new WaitDialog(this);
        mDialog.setMessage("请稍候...");
    }

    private void initData() {
        Intent intent = getIntent();
        userInfo = (UserInfo) intent.getSerializableExtra("userInfo");
        if (myInfo != null && (myInfo.getCommon().contains(userInfo.getUuid()) || myInfo.getDepartmentId().equals(userInfo.getDepartmentId()))) {
            commonCheckbox.setCheckedImmediately(true);
        } else if (myInfo != null) {
            commonCheckbox.setCheckedImmediately(false);
        }
        commonCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!shouldListen) return;
                if (myInfo.getDepartmentId().equals(userInfo.getDepartmentId())) {
                    ToastUtils.showToast("该用户为您的部门同事，不可取消");
                    backUpCheckState();
                    return;
                }
                showWaitingDialog();
                if (isChecked) {
                    //添加为常用联系人
                    addColleague();
                } else {
                    //删除该常用联系人
                    deleteColleague();
                }
            }
        });
        if (!"notimage".equals(userInfo.getAvatar())) {
            if (!StringUtil.isEmpty(userInfo.getAvatar())) {
                Glide.with(DetailContactsActivity.this).load(userInfo.getAvatar()).into(avatar);
                nameTitle.setVisibility(View.GONE);
                //如果是图片才能够点击
                avatar.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent i = new Intent(DetailContactsActivity.this, ContactsAvatarActivity.class);
                        i.putExtra("userinfo", userInfo);
                        startActivity(i);
                    }
                });
            } else {
                avatar.setImageResource(MyListViewAdapter.person_logos[(int) (Math.random() * MyListViewAdapter.person_logos.length - 1)]);
            }
        } else {
            avatar.setImageResource(MyListViewAdapter.person_logos[(int) (Math.random() * MyListViewAdapter.person_logos.length - 1)]);
        }
        if (userInfo.getName() != null) {
            int name_len = userInfo.getName().length();
            if (StringUtilSub.isChinese(userInfo.getName())) {
                nameTitle.setText(userInfo.getName().substring(name_len - 1, name_len));
            } else {
                nameTitle.setText(userInfo.getName().substring(0, 1).toUpperCase());
            }
        }
        nameTV.setText(userInfo.getName());
        positionTV.setText(!TextUtils.isEmpty(userInfo.getPosition()) ? StringUtilSub.SubStringAddCH(0, userInfo.getPosition(), 10) : "");
        groupTV.setText(!TextUtils.isEmpty(userInfo.getDepartment()) ? StringUtilSub.SubStringAddCH(0, userInfo.getDepartment(), 10) : "");
        emailTV.setText(!TextUtils.isEmpty(userInfo.getEmail()) ? userInfo.getEmail() : "");
        phoneTV.setText(!TextUtils.isEmpty(userInfo.getTel()) ? userInfo.getTel() : "");
        mTitleBar.setTitle(userInfo.getDepartment());
        telBtu.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_CALL);
                Uri data = Uri.parse("tel:" + userInfo.getTel());
                intent.setData(data);
                startActivity(intent);
            }
        });

        imBtu.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (mySharedPreferences.getBoolean("RCSconnectStatus", false)) {
                    String uuidString = mySharedPreferences.getString("uuid", "");
                    if (!uuidString.equals(userInfo.getUuid()) && !StringUtil.isEmpty(uuidString)) {
                        /**
                         * 启动单聊界面。
                         */
                        RongIM.getInstance().startConversation(DetailContactsActivity.this, ConversationType.PRIVATE, userInfo.getUuid(), "聊天标题");
                    } else {
                        ToastUtils.showToast("不能和自己聊天");
                    }
                } else {
                    ToastUtils.showToast("IM功能暂时不可用");
                }
            }
        });
        ImageButton emailBut = (ImageButton) findViewById(R.id.emailBut);
        MessagingController.getInstance(getApplication()).addNoRefreshListener(messagingListener);
        assert emailBut != null;
        emailBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                YspProtocolUtils.openEmailClient(DetailContactsActivity.this, "mailto:" + userInfo.getEmail());
            }
        });
    }


    private MessagingListener messagingListener = new MessagingListener() {
        @Override
        public void sendPendingMessagesFailed(Account account) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showToast(R.string.email_send_failed);
                }
            });
        }
    };

    /**
     * 添加到常用联系人
     */
    private void addColleague() {
        String uuid = mySharedPreferences.getString("uuid", "");
        String cid = mySharedPreferences.getString("companyId", "");
        HttpMethods.getInstance().addColleague(uuid, userInfo.getUuid(), cid, new AddColleagueSubscriber());
    }

    /**
     * 删除常用联系人
     */
    private void deleteColleague() {
        String uuid = mySharedPreferences.getString("uuid", "");
        String cid = mySharedPreferences.getString("companyId", "");
        HttpMethods.getInstance().deleteColleague(uuid, userInfo.getUuid(), cid, new DeleteColleagueSubscriber());
    }

    public class AddColleagueSubscriber extends EnterBaseSubscriber {

        @Override
        public void onFailure(String errorMsg) {
            dismissDialog();
            showToast(errorMsg);
            backUpCheckState();
        }

        @Override
        public void onSuccess(JSONObject jsonObject) {
            dismissDialog();
            List<String> list = myInfo.getCommon();
            list.add(userInfo.getUuid());
            saveShared(myInfo);
            showToast("设置成功");
            EventBus.getDefault().post(new YspEvent.RefreshCommonContact());
        }
    }

    class DeleteColleagueSubscriber extends EnterBaseSubscriber {

        @Override
        public void onFailure(String errorMsg) {
            dismissDialog();
            showToast(errorMsg);
            backUpCheckState();
        }

        @Override
        public void onSuccess(JSONObject resultObj) {
            dismissDialog();
            List<String> list = myInfo.getCommon();
            list.remove(userInfo.getUuid());
            saveShared(myInfo);
            showToast("设置成功");
            EventBus.getDefault().post(new YspEvent.RefreshCommonContact());
        }
    }

    private void backUpCheckState() {
        shouldListen = false;
        commonCheckbox.setCheckedImmediately(!commonCheckbox.isChecked());
        shouldListen = true;
    }

    private void showWaitingDialog() {
        mDialog.show();
        commonCheckbox.setEnabled(false);
    }

    private void dismissDialog() {
        mDialog.dismiss();
        commonCheckbox.setEnabled(true);
    }

    @SuppressLint("CommitPrefEdits")
    private void saveShared(UserInfo userInfo) {
        mySharedPreferences.edit().putString(Globals.YSP_USER_INFO, StringUtilSub.base64(userInfo)).commit();
    }

    private void showToast(String str) {
        ToastUtils.showToast(str);
    }

    @Override
    protected void onDestroy() {
        MessagingController.getInstance(getApplication()).removeListener(messagingListener);
        super.onDestroy();
    }
}
